package org.getOffer.offer22;

/**
 * @Author yu
 * @Date 2021/10/25
 */
public class Solution {

    public static void main(String[] args) {

        ListNode listNode1 = new ListNode(1);
        ListNode listNode2 = new ListNode(2);
        ListNode listNode3 = new ListNode(3);
        ListNode listNode4 = new ListNode(4);
        ListNode listNode5 = new ListNode(5);
        listNode1.next = listNode2;
        listNode2.next = listNode3;
        listNode3.next = listNode4;
        listNode4.next = listNode5;

        Solution solution = new Solution();
        ListNode kthFromEnd = solution.getKthFromEnd(listNode1, 1);
        while (true) {
            if (kthFromEnd == null) {
                break;
            }
            System.out.println(kthFromEnd.val);
            kthFromEnd = kthFromEnd.next;
        }

    }

    public ListNode getKthFromEnd(ListNode head, int k) {

        ListNode left = head;
        ListNode right = head;

        int index = 0;

        while (true) {

            if (left == null || right == null) {
                break;
            }

            if (index >= k) {
                left = left.next;
            }

            right = right.next;

            index++;

        }

        return left;

    }

}

class ListNode {
    int val;
    ListNode next;
    ListNode(int x) { val = x; }
}